<template>
	<div>
		商品发布   
		<a-steps :current="current"  class='mb28' @change="onChange" @click='test'>
	      <a-step v-for="(item,index) in steps" :key="item.title" :title="item.title" />
	    </a-steps>
	    <div class="steps-content ">
	    	<a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 8 }" @submit="handleSubmit"> 

	    		<a-row v-if='current == 0'>
					<a-form-item label='商品名称'>
				      <a-input
				        v-decorator="['spuName',formset.spuName ]"  placeholder='请输入商品名称...'
				      />
				    </a-form-item>
				    <a-form-item label='商品类别'>
				    	<a-tree-select
						    v-decorator="['categoryId',formset.categoryId ]"
						    style="width: 100%"
						    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
						    :tree-data="treeData"
						    placeholder="Please select"
						    tree-default-expand-all
						  > 
						</a-tree-select> 
				    </a-form-item> 
				    <a-form-item label='标签'>
				      <a-input
				        v-decorator="['spuTag',formset.spuTag ]"
				      />
				    </a-form-item>
				    <a-form-item label='价格(RMB)'>
				    	<a-input-number v-decorator="['spuPrice',formset.spuPrice ]"  /> 
				    </a-form-item>
				    <a-form-item label='商品轮播图' :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }"> 
				    	
					    <a-upload
					      :action="uploadAddress"
					      list-type="picture-card"
					      :file-list="fileList"
					      :showUploadList = 'false'
					      @preview="handlePreview"
					      @change="handleChange"
					    >
					      <div >
					        <a-icon type="plus" />
					        <div class="ant-upload-text">
					          Upload
					        </div>
					      </div>
					    </a-upload>
						
					    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
					      <img alt="example" style="width: 100%" :src="previewImage" />
					    </a-modal> 

						<draggable v-model="fileList" group="people" @start="drag=true" @end="drag=false"> 
						   <div v-for="(element,index) in fileList" :key="element.uid" class='relative hoverItem mr8' @mouseenter='mouseenter(index)' @mouseleave='mouseleave'>  
						   		<a-tag color="#f50" v-if='index==0' style='position: absolute;'>主图</a-tag>
							   	<img :src='element.url' style="width: 84px;height:84px;">   
							   	<span class='imgHover' v-if='imgHoverShow && index == currentIndex' >
							   		<a-icon type="eye"     class='cursor imgHover_icon '  @click='previewVisible=true' />
							   		<a-icon type="delete"  class='cursor imgHover_icon pl5'  @click='removeFile(index)'  />
							   	</span> 
							   	
						   </div> 
						</draggable> 
				    </a-form-item>
				</a-row>
				<a-row v-if='current == 1'>
					 <a-button class='mb10' icon="edit" @click='addSize'>添加规格</a-button> 
				    <a-form-item label='规格'>
				      <a-input
				        v-decorator="['spuSpecifications',formset.spuSpecifications ]"
				      />
				    </a-form-item>
				    <a-form-item label='库存量'>
				    	<a-input-number v-decorator="['skuInventory',formset.skuInventory ]"   /> 
				    </a-form-item>

				    <a-form-item label='规格'> 
					    <a-input-group compact> 
					      <a-input style='margin-bottom: 10px;width: 50%' default-value="Xihu District, Hangzhou" /> <br>
					      <a-input style='width: 30%' default-value="Xihu District, Hangzhou" />
					    </a-input-group>
					</a-form-item>
				</a-row>
				<a-row v-if='current == 2'>   
				    <a-form-item label='详情' :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }"> 
				      <editor-bar ref='editorForm' v-decorator="['spuDescription',formset.spuDescription]" :isClear="isClear" @change="change"  ></editor-bar>
				    </a-form-item>
				</a-row>

			    <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
			    	<a-button class='mr20'>取消</a-button>
			    	<!-- <a-button type='primary' html-type="submit">确认提交</a-button> -->
			    </a-form-item>
			</a-form> 
	    </div>
	    <div class="steps-action">
	      <a-button v-if="current < steps.length - 1" type="primary" @click="next">
	        Next
	      </a-button>
	      <a-button
	        v-if="current == steps.length - 1"
	        type="primary"
	        @click="$message.success('Processing complete!')"
	      >
	        Done
	      </a-button>
	      <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
	        Previous
	      </a-button>
	    </div>

		
	</div>
</template>	

<script type="text/javascript">
	function getBase64(file) {
	  return new Promise((resolve, reject) => {
	    const reader = new FileReader();
	    reader.readAsDataURL(file);
	    reader.onload = () => resolve(reader.result);
	    reader.onerror = error => reject(error);
	  });
	}

	import { CategoryList,submitCommodity }  from '@/api/minipro/commodity'
	import draggable from 'vuedraggable'
	import EditorBar from '@/components/thirdComponent/wangeditor'
	export default{
		name:'editCommodity',
		data(){
			const steps = [
				{
					title: '商品信息录入',
					content: 'First-content',
				},
				{
					title: '库存/规格',
					content: 'Second-content',
				},
				{
					title: '商品详情',
					content: 'Second-content',
				},
				]
			return {
				_isEdit:false,
				formset:{
					spuName : { rules:[{required:true,message:'dddd'}] },
					categoryId : {  },
					categoryId : {  },
					spuTag : {  },
					spuPrice : {  },
					spuSpecifications : {  },
					spuSpecifications : {  },
					commodityImageVOList : {  },
					spuDescription : {  },
				},
				treeData:[],
				uploadAddress:process.env.BASE_API+'/op/fileupload/upload_file',/*upload_requesturl*/
				imgAddress:process.env.BASE_API+'/op/fileupload/download_file?fileCode=',
				fileList: [
			        {
			          uid: '1',
			          name: 'image.png',
			          status: 'done',
			          url: process.env.BASE_API+'/op/fileupload/download_file?fileCode='+'94863228-f533-4f74-8785-bac0a2ae92e9',
			        },
			        {
			          uid: '2',
			          name: 'image.png',
			          status: 'done',
			          url: process.env.BASE_API+'/op/fileupload/download_file?fileCode='+'80fc7283-f6d7-459d-b130-2145c60f92e0',
			        }, 
			    ],
			    previewVisible:false,	

			    myArray:[{id:1,name:'lalala'},{id:2,name:'ddefe'},{id:3,name:'girl'}],
			    imgHoverShow:false,//img显示与否	
			    currentIndex:null,
			    isClear: false,

			    current: 0,
			    steps,
				
			}
		},
		beforeCreate(){
			this.form = this.$form.createForm(this)
		},
		created(){
			this.categoryInit()
		},
		methods:{
			next() {
		      this.current++;
		      if(this.current == 0){
		      	//新增spu
		      	let url = this._isEdit == true ? '/sys/commodity_spu/modify_commodity_spu' : '/sys/commodity_spu/create_commodity_spu'
		    	e.preventDefault()
		    	this.form.validateFields((err, values) => {
		    		console.log(values)
		        	if (!err) {
		        		submitCommodity(url,values).then((res)=>{
		        			this.$message.success(res.data.msg)
		        		})
		        	}
		        })

		      }
		    },
		    prev() {
		      this.current--;
		    },
		    /*
				添加规格
		    */ 
		    addSize(){

		    },


			categoryInit(){
				CategoryList().then((res)=>{
					let data = res.data.dataList
					this.treeData =this.ParentChildTree(data)
					 
				})
			},

			/*
				将返回的数组按树结构排列
			*/
			ParentChildTree(arr){
				let level = []
				for(let i=0;i<arr.length;i++){
					if(arr[i].parentId == 4){
						level.push({
							 
							value : arr[i].id,
							title : arr[i].categoryName,
							parentId : arr[i].parentId
						})
					}
				}

				nextChildTree(level)

				function nextChildTree(readyArr){
					for(let j=0;j<readyArr.length;j++){
						let child = []
						for(let p = 0;p<arr.length;p++){
							if(readyArr[j].value == arr[p].parentId){
								child.push({ 
									value : arr[p].id,
									title : arr[p].categoryName,
									parentId : arr[p].parentId
								})
							}
						} 
						
						if(child.length > 0){
							readyArr[j].children = child
							nextChildTree(child)
						}
					} 
				}

				return level
			},  

			handleCancel() {
		      this.previewVisible = false;
		    },
		    async handlePreview(file) {
				if (!file.url && !file.preview) {
					file.preview = await getBase64(file.originFileObj);
				}
				this.previewImage = file.url || file.preview;
				this.previewVisible = true;
		    },
		    handleChange({ file,fileList }) {
		    	
		    	fileList = fileList.map(file => {
			        if (file.response) {
			          // Component will show file.url as link
			          file.url = this.imgAddress + file.response.data.code;
			        }
			        return file;
			      });
			    this.fileList = fileList;
			    console.log(this.fileList)
			},
			hover(e){
				console.log(e)
			},
			mouseenter(num){ 
				this.imgHoverShow=true
				this.currentIndex = num 
			},
			mouseleave(e){
				 
				this.imgHoverShow=false
				this.currentIndex = null 
			},
			removeFile(index){
				this.fileList.splice(index,1)

			},
			change(val) {
		      console.log(val) 
		    },
		    handleSubmit(e){
		    	let url = this._isEdit == true ? '/sys/commodity_spu/modify_commodity_spu' : '/sys/commodity_spu/create_commodity_spu'
		    	e.preventDefault()
		    	this.form.validateFields((err, values) => {
		    		console.log(values)
		        	if (!err) {
		        		submitCommodity(url,values).then((res)=>{
		        			this.$message.success(res.data.msg)
		        		})
		        	}
		        })
  
		    },
		    onChange(current) {
		      console.log('onChange:', current);
		      this.current = current;
		    },
		    test(e){
		    	console.log(e)
		    }
		},
		components: {
            draggable,
            EditorBar
        },
	}
</script>

<style scoped="scoped">
	.hoverItem{ display: inline-block; padding: 10px;border:1px solid #ddd;border-radius: 10px;  }
	.imgHover{ position: absolute;width: 84px;height: 84px;background:rgba(0,0,0,0.5);left:10px;text-align: center; padding-top: 30px; /*pointer-events: none;*/}
	.imgHover_icon{ color:rgba(255,255,255,0.8); font-size: 16px; }
</style>